<?php

namespace App\Http\Model;

use App\Lib\Publisher;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class Trends extends Base
{
    protected $table = 'trends_content';
    protected $likeTable = 'trends_content_like';
    protected $countTable = 'trends_zpzy_count';
    protected $commentTable = 'trends_comment';
    protected $commentLikeTable = 'trends_comment_like';
    protected $replyLikeTable = 'trends_reply_like';
    protected $replyTable = 'trends_reply';
    protected $trendsAdTable = 'trends_ad';
    protected $trendGreetLogTable = 'trend_greet_log';

    public $timestamps = false;

    private $cacheTrends = 'CACHE:TRENDS';
    protected $redisKeyTrendsAuditSwitch = 'TRENDS:AUDIT:SWITCH';
    protected $redisKeyTrendsRECOMMEND = 'TRENDS:RECOMMEND';
    protected $redisKeyTrendsReadLimit = 'TRENDS:READ:LIMIT:';
    protected $redisTrendsAd = 'TRENDS:AD';
    protected $redisTrendJx = 'TRENDS:JX:'; //精选动态
    protected $redisTrendsGreet = 'TRENDS:GREET';
    protected $redisTrendsLastSelectGender = 'TRENDS:LAST:SELECT:GENDER';
    protected $fields = ['content_id', 'user_id', 'c_content', 'c_imgs', 'c_video', 'c_voice', 'c_cover', 'c_type', 'position_name', 'p_lat', 'p_lng', 'create_timestamp', 'c_voice_time', 'cp_data', 'type', 'state','works_id', 'long_img', 'handbook_id'];

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    public function getCtypeMap($key=0){
        $list = [
            1=>'文字',
            2=>'图片',
            3=>'视频',
            4=>'语音',
            5=>'cp消息',
            6=>'同步到我的作品',
            7=>'活动分享',
        ];
        if($key){
            return $list[$key] ?? '';
        }
        return $list;
    }

    /**
     * @desc 动态推荐列表
     * */
    public function trends_recommend_list($page, $page_size, $min_time, $ids, $currUserId = 0)
    {
        $document = DB::table($this->table)
            ->where(['is_delete' => 0, 'state' => 1])
            ->whereIn('content_id', $ids);

        if ($min_time > 0) {
            $document->where('create_timestamp', '>=', $min_time);
        }

        // 当前登录用户可以获取自己的审核状态的数据
        /*if ($currUserId > 0) {
            $document->orWhere(['is_delete' => 0])
                ->whereIn('content_id', $ids)
                ->where([$this->table.'.user_id' => $currUserId]);

            if ($min_time > 0) {
                $document->where('create_timestamp', '>=', $min_time);
            }
        }*/

        $result = $document
            ->orderBy('type', 'desc')
            ->orderBy('create_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($this->fields);

        $result = self::objToArray($result);
        return $this->resource_build($result);
    }

    /**
     * @desc 动态最新列表
     * */
    public function trends_new_list($ctype,$page, $page_size, $min_time, $currUserId = 0 ,$is_show_works=false)
    {
        $fields = ['content_id', 'trends_content.user_id as user_id', 'c_content', 'c_imgs', 'c_video','c_voice', 'c_cover', 'c_type', 'position_name', 'p_lat', 'p_lng', 'trends_content.create_timestamp as create_timestamp', 'c_voice_time','cp_data', 'type', 'state','works_id', 'trends_content.long_img', 'trends_content.handbook_id'];
        //改动by：wangxf
        //增加查询条件:m_type。用于筛选消息人为发送||系统发送

            $document = DB::table($this->table)
                ->leftJoin('user', 'trends_content.user_id', '=', 'user.user_id')
                ->where(['is_delete' => 0, 'active_certify' => 1, 'state' => 1,'m_type'=>1]);

        if($page_size==5){
//            write_log('error_trends_liya', 'trends_ctype55',$ctype );
            $document->where('c_type','=' ,3);

        }else{
            $document->where('c_type','!=' ,3);
        }
        //判断作品，低版本不显示作品
        if(!$is_show_works){
            $document->where('c_type','!=' ,6);

        }
        // ->where('create_timestamp', '>=', $min_time)

        // 当前登录用户可以获取自己的审核状态的数据
        /*if ($currUserId > 0) {
            $document->orWhere(['is_delete' => 0])
                ->where([$this->table.'.user_id' => $currUserId, 'active_certify' => 1]);
        }*/
    if($ctype==3){
        $result = $document
            ->inRandomOrder()->take(5)
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($fields);
    }else{
        $result = $document->orderBy('create_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($fields);
    }
        $result = self::objToArray($result);
        return $this->resource_build($result);
    }

    /**
     * @desc 动态附近列表
     * */
    public function trends_near_list($page,$page_size,$position_range, $currUserId = 0)
    {
        $document = DB::table($this->table)
            ->where(['is_delete' => 0, 'state' => 1])
            ->where('p_lat', '<', $position_range['maxLat'])
            ->where('p_lat', '>', $position_range['minLat'])
            ->where('p_lng', '>', $position_range['minLng'])
            ->where('p_lng', '<', $position_range['maxLng']);

        // 当前登录用户可以获取自己的审核状态的数据
        /*if ($currUserId > 0) {
            $document->orWhere(['is_delete' => 0])
                ->where('p_lat', '<', $position_range['maxLat'])
                ->where('p_lat', '>', $position_range['minLat'])
                ->where('p_lng', '>', $position_range['minLng'])
                ->where('p_lng', '<', $position_range['maxLng'])
                ->where([$this->table.'.user_id' => $currUserId]);
        }*/

        $result = $document->orderBy('create_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($this->fields);

        $result = self::objToArray($result);
        return $this->resource_build($result);
    }

    /**
     * @desc 动态声控列表
     * */
    public function trends_voice_list($page,$page_size, $currUserId = 0)
    {
        $fields = ['content_id', 'trends_content.user_id as user_id', 'c_content', 'c_imgs', 'c_video','c_voice', 'c_cover', 'c_type', 'position_name', 'p_lat', 'p_lng', 'trends_content.create_timestamp as create_timestamp', 'c_voice_time','cp_data'];
        $document = DB::table($this->table)
            ->leftJoin('user', 'trends_content.user_id', '=', 'user.user_id')
            ->where('active_certify', '=', 1)
            ->where(['is_delete' => 0, 'c_type' => 4, 'state' => 1])
            ->orderBy('create_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($fields);
        $result = self::objToArray($document);
        return $this->resource_build($result);
    }

    /**
     * @desc 动态声控
     *
     * @param array $contentIds 动态内容数组ID
     * @return array
     * */
    public function get_trends_voice_by_ids($contentIds)
    {
        if (empty($contentIds)){
            return [];
        }
        $data = Redis::MGET(array_map(function ($trendId){
            return $this->cacheTrends . ':' . $trendId;
        }, $contentIds));

        $data_count = count($data);
        for ($i = 0; $i < $data_count; $i++){
            if (!empty($data[$i])){
                $itemData = json_decode($data[$i], true);
                $data[$i] = $itemData;
                unset($contentIds[$i]);
            }
            else{
                unset($data[$i]);
            }
        }

        if (empty($contentIds)){
            return array_values($data);
        }

        $fields = ['content_id', 'trends_content.user_id as user_id', 'c_content', 'c_imgs', 'c_video','c_voice', 'c_cover', 'c_type', 'position_name', 'p_lat', 'p_lng', 'trends_content.create_timestamp as create_timestamp', 'c_voice_time','cp_data', 'type', 'state'];
        $document = DB::table($this->table)
            ->leftJoin('user', 'trends_content.user_id', '=', 'user.user_id')
            ->where('active_certify', '=', 1)
            ->where(['is_delete'=>0,'c_type' => 4, 'state' => 1])
            ->whereIn('content_id',$contentIds)
            ->orderBy('create_timestamp', 'desc')
            ->get($fields);
        $result = self::objToArray($document);
        $result = $this->resource_build($result);

        for ($i = 0; $i < count($result); $i++){
            array_push($data, $result[$i]);
            Redis::SET($this->cacheTrends . ':' . $result[$i]['content_id'], json_encode($result[$i]), 'EX', 3600);
        }
        return array_values($data);
    }

    /**
     * @desc 动态关注列表
     * */
    public function trends_follow_list($page,$page_size,$ids,$genders,$is_show_works=false)
    {
        //判断作品，低版本不显示作品
        if(!$is_show_works){
            $document = DB::table($this->table)
                ->where(['is_delete'=>0, 'state' => 1, 'm_type' => 1])
                ->where('c_type' ,'!=',6)
                ->where('c_type' ,'!=',3)
                ->whereIn('user_id',$ids)
                ->whereIn('gender_type' ,$genders)
                ->orderBy('create_timestamp', 'desc')
                ->offset(($page) * $page_size)
                ->limit($page_size)
                ->get($this->fields);
        }else{
            $document = DB::table($this->table)
                ->where(['is_delete'=>0, 'state' => 1, 'm_type' => 1])
                ->where('c_type' ,'!=',3)
                ->whereIn('user_id',$ids)
                ->whereIn('gender_type' ,$genders)
                ->orderBy('create_timestamp', 'desc')
                ->offset(($page) * $page_size)
                ->limit($page_size)
                ->get($this->fields);
        }
        $result = self::objToArray($document);
        $result = $this->resource_build($result);
        return $result;
    }

    /**
     * @desc 动态粉丝列表
     * */
    public function trends_fans_list($page,$page_size,$ids)
    {
        $document = DB::table($this->table)
            ->leftJoin('user', 'trends_content.user_id', '=', 'user.user_id')
            ->where('active_certify', '=', 1)
            ->where(['is_delete'=>0, 'state' => 1])
            ->whereIn('trends_content.user_id',$ids)
            ->orderBy('create_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($this->fields);
        $result = self::objToArray($document);
        $result = $this->resource_build($result);
        return $result;
    }

    /**
     * @desc 男女类型发布动态列表
     * */
    public function trendsGenderTypeList($page, $page_size, $genderType)
    {
        $document = DB::table($this->table)
            ->where(['is_delete' => 0, 'gender_type' => $genderType, 'state' => 1])
            ->orderBy('create_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($this->fields);

        $result = self::objToArray($document);
        $result = $this->resource_build($result);
        return $result;
    }

    /**
     * @desc 获取精选类型发布动态列表
     * */
    public function getDelicateTypeList($page, $page_size,$gender=2 ,$user_id=0,$is_show_works=false)
    {
        if($page ==0){
            $res = Redis::get($this->redisTrendJx.$page.':'.$gender);
            if(!empty($res)){
                return json_decode($res ,true);
            }
        }
        //判断作品，低版本不显示作品
        if(!$is_show_works){
            $document = DB::table($this->table)
                ->where(['is_delete' => 0, 'type' => 1, 'state' => 1])
                ->where('c_type','!=',6)
                ->where(function ($query) use ($gender,$user_id) {
                    $query->where('gender_type',$gender)
                        ->orWhere('user_id',$user_id);
                })
                ->orderBy('create_timestamp', 'desc')
                ->offset(($page) * $page_size)
                ->limit($page_size)
                ->get($this->fields);
        }else{
            $document = DB::table($this->table)
//            ->where(['is_delete' => 0, 'type' => 1, 'state' => 1 ,'gender_type'=>$gender])
                ->where(['is_delete' => 0, 'type' => 1, 'state' => 1])
                ->where(function ($query) use ($gender,$user_id) {
                    $query->where('gender_type',$gender)
                        ->orWhere('user_id',$user_id);
                })
                ->orderBy('create_timestamp', 'desc')
                ->offset(($page) * $page_size)
                ->limit($page_size)
                ->get($this->fields);
        }

        $result = self::objToArray($document);
        $result = $this->resource_build($result);
        if($page == 0 && !empty($result)){
            Redis::setex($this->redisTrendJx.$page.':'.$gender ,5*60 ,json_encode($result));
        }
        return $result;
    }


    /**动态-全部
     * @param $page
     * @param $page_size
     * @param $genders
     * @param $user_ids
     * @param $is_show_works
     * @return mixed
     */
    public function getAllTrendsList($page, $page_size,$genders ,$user_ids,$is_show_works=false)
    {
        //判断作品，低版本不显示作品
        if(!$is_show_works){
            $document = DB::table($this->table)
                ->where(['is_delete' => 0, 'state' => 1, 'm_type'=>2])
                ->where('c_type' ,'!=' ,6)
                ->where('c_type' ,'!=' ,3)
                ->whereIn('gender_type',$genders)
                ->where(function ($query) use ($user_ids) {
                    $query->where('type',3)
                        ->orWhereIn('user_id',$user_ids);
                })
                ->orderBy('create_timestamp', 'desc')
                ->offset(($page) * $page_size)
                ->limit($page_size)
                ->get($this->fields);
        }else{
            $document = DB::table($this->table)
                ->where(['is_delete' => 0, 'state' => 1,'m_type'=>2])
                ->whereIn('gender_type',$genders)
                ->where(function ($query) use ($user_ids) {
                    $query->where('type',3)
                        ->orWhereIn('user_id',$user_ids);
                })
                ->orderBy('create_timestamp', 'desc')
                ->offset(($page) * $page_size)
                ->limit($page_size)
                ->get($this->fields);
        }


        $result = self::objToArray($document);
        $result = $this->resource_build($result);
        return $result;
    }
    /**
     * 查看用户的动态
     * @param $page
     * @param $page_size
     * @param $user_id
     * @param $currUserId
     * @param $is_show_works
     * @return mixed
     */
    public function user_trends_list($page,$page_size,$user_id, $currUserId = 0 ,$is_show_works = false)
    {
        $document = DB::table($this->table)->where(['user_id' => $user_id, 'is_delete' => 0, 'state' => 1]);
        //判断作品，低版本不显示作品
        if(!$is_show_works){
            $document->where('c_type','!=',6);
        }
        // 只能自己查看自己的所有动态
        if ($currUserId > 0 and $user_id == $currUserId) {
            if(!$is_show_works){
                $whereOr[] =  ['c_type', '!=', 6];
                $whereOr[] = ['user_id' ,'=' ,$user_id];
                $document->orWhere($whereOr)
                    ->where(['is_delete' => 0]);
            }else{
                $document->orWhere(['user_id' => $user_id])
                    ->where(['is_delete' => 0]);
            }
        }

        $result = $document->orderBy('create_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($this->fields);
        $result = self::objToArray($result);
        $result = $this->resource_build($result);
        return $result;
    }


    /**
     * 获得内容信息
     * @param $id
     * @return mixed
     */
    public function trend($id){
        $document = DB::table($this->table)
            ->where(['is_delete'=>0])
            ->where(['content_id'=>$id])
            ->get($this->fields);
        if (empty($document)){
            return null;
        }
        $result = self::objToArray($document);
        $result = $this->resource_build($result);
        if (empty($result)){
            return null;
        }
        return $result[0];
    }


    /**
     * 添加动态禁止评论用户
     * @param $contentId
     * @param $userId
     */
    public function blockUser($contentId, $userId){
        DB::table('trends_block')->insert([
            'content_id' => $contentId,
            'block_user_id' => $userId,
            'create_timestamp' => time(),
        ]);
    }


    /**
     * 查看用户是否被屏蔽
     * @param $contentId
     * @param $userId
     * @return bool
     */
    public function isBlock($contentId, $userId){
        $count = DB::table('trends_block')->where([
                'content_id' => $contentId,
                'block_user_id' => $userId,
        ])->count();
        if ($count > 0){
            return true;
        }
        return false;
    }

    /**
     * @desc 文件处理
     * */
    private function resource_build($list)
    {
        if(!empty($list)){
            $picDomain = getPicDomain();
            foreach($list as $k=>$v){
                if(!empty($v['c_video'])){
                    $list[$k]['c_video'] = $picDomain.$v['c_video'];
                }
                if(!empty($v['c_voice'])){
                    $list[$k]['c_voice'] = $picDomain.$v['c_voice'];
                }
                if(!empty($v['c_imgs'])){
                    $temp_arr = explode(',',$v['c_imgs']);
                    foreach($temp_arr as $key=>$val){
                        $temp_arr[$key] = $picDomain.$val. '?x-oss-process=style/thumbnails';
                    }
                    $list[$k]['c_thumbnails_imgs'] = implode(',',$temp_arr);
                    $temp_arr = explode(',',$v['c_imgs']);
                    foreach($temp_arr as $key=>$val){
                        $temp_arr[$key] = $picDomain.$val;
                    }
                    $list[$k]['c_imgs'] = implode(',',$temp_arr);
                }
                if(!empty($v['c_cover'])){
                    $temp_arr = explode(',',$v['c_cover']);
                    foreach($temp_arr as $key=>$val){
                        $str_url = strtolower($val);
                        $top_str = substr($str_url, 0, 4);
                        if ($top_str == 'http'){
                            $temp_arr[$key] = $val;
                        }else{
                            $temp_arr[$key] = $picDomain.$val;
                        }
                    }
                    $list[$k]['c_cover'] = implode(',',$temp_arr);
                }

                // CP喜结良缘数据读取
                $cpData = $v['cp_data'] ?? '';
                if(!empty($cpData)) {
                    json_decode($cpData);
                    if (json_last_error() == JSON_ERROR_NONE) {
                        $cpData = json_decode($cpData, true);
                        if(!empty($cpData)) {
                            $userImages = $cpData['user']['images'] ?? [];
                            // 添加图片地域
                            foreach ($userImages as $key => $value) {
                                $cpData['user']['images'][$key] = $picDomain . $value;
                            }
                            $cpData['ring']['image'] = $picDomain . $cpData['ring']['image'];
                            $cpData['ring']['gray_image'] = $picDomain . $cpData['ring']['gray_image'];

                            $list[$k]['cp_data'] = json_encode($cpData, JSON_UNESCAPED_UNICODE);
                        }
                    }
                }

                if ($v['c_type'] == 2 && !$v['c_imgs']) {// 等于2表示图文，如果没有图片，则更改为纯文字模式
                    $list[$k]['c_type'] = 1;
                }
            }
        }
        return $list;
    }


    /**
     * @desc 写入动态
     * */
    public function trends_add($data)
    {
       $content_id = DB::table($this->table)->insertGetId($data);
       if($content_id){
           DB::table($this->countTable)->insert(['content_id' => $content_id,'create_timestamp' => time()]);
       }
        $document = DB::table($this->table)
            ->where(['is_delete'=>0, 'content_id' => $content_id ])
            ->get($this->fields);
        $result = self::objToArray($document);
        $result = $this->resource_build($result);

        return $result;
    }

    /**
     * @desc 删除动态
     * */
    public function trends_del($user_id,$content_id)
    {
        Redis::DEL($this->cacheTrends . ':' . $content_id);
        $this->trendsRemoveRecommend($content_id);
        return DB::table($this->table)->where(['user_id'=> $user_id,'content_id' => $content_id])->update(['is_delete' => 1]);
    }


    /**
     * 清理用户动态
     * @param $userId
     * @return int
     */
    public function cleanUserTrends($userId){
        DB::table($this->table)
            ->where(['user_id'=> $userId])
            ->update(['is_delete' => 1]);
        DB::table($this->replyTable)
            ->where(['from_user_id'=> $userId])
            ->delete();
        DB::table($this->commentTable)
            ->where(['user_id'=>$userId])
            ->delete();
    }


    /**
     * 删除回复
     * @param $user_id
     * @param $reply_id
     * @return int
     */
    public function trends_reply_del($user_id,$reply_id)
    {
        return DB::table($this->replyTable)->where(['from_user_id'=> $user_id, 'id' => $reply_id])->delete();
    }

    /**
     * 删除评论
     * @param $user_id
     * @param $reply_id
     * @return int
     */
    public function trends_comment_del($comment_id)
    {

        return !($contentID = DB::table($this->commentTable)
                ->where([ 'comment_id' => $comment_id])
                ->first(['content_id']))
        || !DB::table($this->commentTable)->where(['comment_id' => $comment_id])->delete()
        || DB::table($this->countTable)->where(['content_id' => $contentID->content_id])->decrement('comment_count');
    }

    /**
     * @desc 内容赞
     * @param int $act_type [操作类型] [1：点赞 0：取消点赞]
     * */
    public function trends_like($user_id,$content_id,$act_type)
    {

        $document = DB::table($this->likeTable)->where(['content_id'=>$content_id,'user_id'=>$user_id])->first();
        $check_ret = self::objToArray($document);
        $t = 0;
        if($act_type == 1){
            if(empty($check_ret)){
                DB::table($this->likeTable)->insert(['content_id'=>$content_id,'user_id'=>$user_id,'create_timestamp'=>time()]);
                $t = 1;
            }else{
                if($check_ret['is_cancel']){
                    $t = 1;
                    DB::table($this->likeTable)->where(['content_id'=>$content_id,'user_id'=>$user_id])->update(['is_cancel'=>0]);
                }
            }

        }else{
            if(!$check_ret['is_cancel']){
                DB::table($this->likeTable)->where(['content_id'=>$content_id,'user_id'=>$user_id])->update(['is_cancel'=>1]);
                $t = -1;
            }
        }

        return DB::table($this->countTable)->where(['content_id' => $content_id])->increment('like_count',$t);

    }

    /**
     * 用户是否点赞
     * @param $user_id
     * @param $content_id
     */
    public function trends_like_exist($user_id, $content_id){
        $count = DB::table($this->likeTable)->where(['content_id' => $content_id, 'user_id'=>$user_id, 'is_cancel'=>0])->count();
        if ($count > 0){
            return true;
        }
        return false;
    }




    /**
     * @desc 评论赞
     * @param int $act_type [操作类型] [1：点赞 0：取消点赞]
     * */
    public function trends_comment_like($user_id,$comment_id,$act_type)
    {
        $document = DB::table($this->commentLikeTable)->where(['comment_id'=>$comment_id,'user_id'=>$user_id])->first();
        $check_ret = self::objToArray($document);

        $t = 0;
        if($act_type == 1){
            if(empty($check_ret)){
                DB::table($this->commentLikeTable)->insert(['comment_id'=>$comment_id,'user_id'=>$user_id,'create_timestamp'=>time()]);
                $t = 1;
            }else{
                if($check_ret['is_cancel']){
                    $t = 1;
                    DB::table($this->commentLikeTable)->where(['comment_id'=>$comment_id,'user_id'=>$user_id])->update(['is_cancel'=>0]);
                }
            }
        }else{
            if(!$check_ret['is_cancel']){
                $t = -1;
                DB::table($this->commentLikeTable)->where(['comment_id'=>$comment_id,'user_id'=>$user_id])->update(['is_cancel'=>1]);
            }
        }

        return DB::table($this->commentTable)->where(['comment_id' => $comment_id])->increment('l_count',$t);

        return true;
    }


    /**
     * 评论是否点赞
     * @param $user_id
     * @param $comment_id
     */
    public function trends_comment_like_exist($user_id, $comment_id){
        $count = DB::table($this->commentLikeTable)->where(['comment_id' => $comment_id, 'user_id'=>$user_id, 'is_cancel'=>0])->count();
        if ($count > 0){
            return true;
        }
        return false;
    }



    /**
     * @desc 回复赞
     * @param int $act_type [操作类型] [1：点赞 0：取消点赞]
     */
    public function trends_reply_like($user_id,$reply_id,$act_type)
    {
        $document = DB::table($this->replyLikeTable)->where(['reply_id'=>$reply_id,'user_id'=>$user_id])->first();
        $check_ret = self::objToArray($document);

        if($act_type == 1){
            if(empty($check_ret)){
                DB::table($this->replyLikeTable)->insert(['reply_id'=>$reply_id,'user_id'=>$user_id,'create_timestamp'=>time()]);
            }else{
                if($check_ret['is_cancel']){
                    DB::table($this->replyLikeTable)->where(['reply_id'=>$reply_id,'user_id'=>$user_id])->update(['is_cancel'=>0]);
                }
            }
        }else{
            if(!$check_ret['is_cancel']){
                DB::table($this->replyLikeTable)->where(['reply_id'=>$reply_id,'user_id'=>$user_id])->update(['is_cancel'=>1]);
            }
        }

        return true;
    }


    /**
     * 回复是否点赞
     * @param $user_id
     * @param $comment_id
     */
    public function trends_reply_like_exist($user_id, $reply_id){
        $count = DB::table($this->replyLikeTable)->where(['reply_id' => $reply_id, 'user_id'=>$user_id, 'is_cancel'=>0])->count();
        if ($count > 0){
            return true;
        }
        return false;
    }



    /**
     * @desc 阅读
     * */
    public function trends_read($content_id, $user_id)
    {
        $r_name = 'Trends:readLimit:';
        $key = $r_name . $user_id . '.' . $content_id;
        $start_time = strtotime(date("Y-m-d",strtotime("+0 day")));   //
        $end_time = $start_time+24 * 60 * 60-1-time();  //时间段内不计算阅读量

        //暂定为点击即 +1
        $t = 1;
        if (!Redis::get($key)) {
            Redis::setex($key, $end_time, $t);
            return  DB::table($this->countTable)->where(['content_id' => $content_id])->increment('read_count', $t);
        }
        return false;

    }

    /**
     * @desc 转发计数
     * */
    public function trends_relay($content_id, $user_id)
    {
        $r_name = 'Trends:relayLimit:';
        $key = $r_name . $user_id . '.' . $content_id;
        $value = 1;
        if (!Redis::get($key)) {

            $t = 1;
            Redis::setex($key, 3600, $value);
            return DB::table($this->countTable)->where(['content_id' => $content_id])->increment('relay_count', $t);

        }
        return true;
    }

    /**
     * @desc 评论
     * */
    public function trends_comment($data)
    {
        $comment_id = DB::table($this->commentTable)->insertGetId($data);
        $condition = ['comment_id' => $comment_id];
        $fields = [ 'comment_id','content_id', 'user_id', 'comment_text', 'comment_voice','create_timestamp','p_lng','p_lat', 'comment_voice_time','comment_img'];
        $document = DB::table($this->commentTable)
            ->where($condition)
            ->get($fields);

        $result = self::objToArray($document);
        $comment_ids = [];
        $user_ids = [];
        if(!empty($result)){
            foreach($result as $k=>$v){
                if($v['comment_voice']){
                    $result[$k]['comment_voice'] = getPicDomain().$v['comment_voice'];
                }
                if($v['comment_img']){
                    $img_arr = explode(",",$v['comment_img']);
                    $thumb_img = [];
                    foreach ($img_arr as &$img) {
                        $img = getPicDomain().$img;
                        array_push($thumb_img,$img . "?x-oss-process=style/thumbnails");
                    }
                    unset($img);
                    //大图
                    $img_str = implode(",",$img_arr);
                    $result[$k]['comment_img'] = $img_str;

                    //缩略图
                    $thumb_str = implode(",",$thumb_img);
                    $result[$k]['thumb_comment_img'] = $thumb_str;
                }
                $comment_ids[] = $v['comment_id'];
                $user_ids[] = $v['user_id'];
            }
        }
        //回复数
        $reply_count_arr = [];
        if(!empty($comment_ids)){
            $reply_count_arr = $this->reply_count($comment_ids);
        }
        //点赞数
        $like_count_arr = [];
        if(!empty($comment_ids)){
            $like_count_arr = $this->trends_comment_like_count($comment_ids);
        }
        if(!empty($result)){
            foreach($result as $k=>$v){
                $result[$k]['reply_count'] = isset($reply_count_arr[$v['comment_id']])?$reply_count_arr[$v['comment_id']]:0;
                $result[$k]['like_count'] = isset($like_count_arr[$v['comment_id']])?$like_count_arr[$v['comment_id']]:0;
            }
        }

        return ['list'=>$result,'user_ids'=>$user_ids];
    }

    /**
     * @desc 回复
     * */
    public function trends_reply($data)
    {
        $reply_id = DB::table($this->replyTable)->insertGetId($data);
        $condition = ['id' => $reply_id];
        $fields = [ 'id as reply_id','comment_id', 'reply_type', 'reply_content', 'reply_voice','from_user_id','to_user_id','create_timestamp','p_lng','p_lat','reply_voice_time','reply_img', 'content_id'];
        $document = DB::table($this->replyTable)
            ->where($condition)
            ->get($fields);

        $result = self::objToArray($document);
        $f_user_ids = [];
        $t_user_ids = [];
        $reply_ids = [];
        if(!empty($result)){
            foreach($result as $k=>$v){
                if($v['reply_voice']){
                    $result[$k]['reply_voice'] = getPicDomain().$v['reply_voice'];
                }
                if($v['reply_img']){
                    $img_arr = explode(",",$v['reply_img']);
                    $thumb_img = [];
                    foreach ($img_arr as &$img){
                        $img = getPicDomain().$img;
                        array_push($thumb_img,$img."?x-oss-process=style/thumbnails");
                    }
                    unset($img);
                    //大图
                    $img_str = implode(",",$img_arr);
                    $result[$k]['reply_img'] = $img_str;

                    //缩略图
                    $thumb_str = implode(",",$thumb_img);
                    $result[$k]['thumb_reply_img'] = $thumb_str;
                }
                $f_user_ids[] = $v['from_user_id'];
                $t_user_ids[] = $v['to_user_id'];
                $reply_ids[] = $v['reply_id'];
            }
        }

        if(!empty($reply_ids)){
            $like_count_arr = $this->trends_reply_like_count($reply_ids);
        }

        if(!empty($result)){
            foreach($result as $k=>$v){
                $result[$k]['like_count'] = isset($like_count_arr[$v['reply_id']])?$like_count_arr[$v['reply_id']]:0;
            }
        }

        return ['list'=>$result,'f_user_ids'=>$f_user_ids,'t_user_ids'=>$t_user_ids];
    }

    /**
     * @desc 获取一条评论
     * */
    public function get_comment($comment_id)
    {
        $fields = ['content_id', 'user_id'];
        $document = DB::table($this->commentTable)->where(['comment_id' => $comment_id])->first($fields);
        return self::objToArray($document);
    }

    /**
     * @desc 获取一条回复
     * */
    public function get_reply($id)
    {
        $fields = ['from_user_id'];
        $document = DB::table($this->replyTable)->where(['id' => $id])->first($fields);
        return self::objToArray($document);
    }

    /**
     * @desc 评论计数
     * */
    public function trends_comment_count($content_id)
    {
        $t = 1;
        return DB::table($this->countTable)->where(['content_id' => $content_id])->increment('comment_count',$t);
    }

    /**
     * @desc 评论列表
     * */
    public function comments_list($content_id,$page,$page_size)
    {
        $condition = ['content_id' => $content_id];
        $fields = [ 'comment_id','content_id', 'user_id', 'comment_text', 'comment_voice','create_timestamp','p_lng','p_lat', 'comment_voice_time','comment_img'];
        $document = DB::table($this->commentTable)
            ->where($condition)
            ->orderBy('l_count', 'desc')
            ->orderBy('create_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($fields);
        $result = self::objToArray($document);
        $comment_ids = [];
        $user_ids = [];
        if(!empty($result)){
            foreach($result as $k=>$v){
                if($v['comment_voice']){
                    $result[$k]['comment_voice'] = getPicDomain().$v['comment_voice'];
                }

                if($v['comment_img']){
                    $img_arr = explode(",",$v['comment_img']);
                    $thumb_img = [];
                    foreach ($img_arr as &$img){
                        $img = getPicDomain().$img;
                        array_push($thumb_img,$img."?x-oss-process=style/thumbnails");
                    }
                    unset($img);
                    //大图
                    $img_str = implode(",",$img_arr);
                    $result[$k]['comment_img'] = $img_str;

                    //缩略图
                    $thumb_str = implode(",",$thumb_img);
                    $result[$k]['thumb_comment_img'] = $thumb_str;
                }
                $comment_ids[] = $v['comment_id'];
                $user_ids[] = $v['user_id'];
            }
        }
        //回复数
        $reply_count_arr = [];
        if(!empty($comment_ids)){
            $reply_count_arr = $this->reply_count($comment_ids);
        }
        //点赞数
        $like_count_arr = [];
        if(!empty($comment_ids)){
            $like_count_arr = $this->trends_comment_like_count($comment_ids);
        }
        if(!empty($result)){
            foreach($result as $k=>$v){
                $result[$k]['reply_count'] = isset($reply_count_arr[$v['comment_id']])?$reply_count_arr[$v['comment_id']]:0;
                $result[$k]['like_count'] = isset($like_count_arr[$v['comment_id']])?$like_count_arr[$v['comment_id']]:0;
            }
        }


        return ['list'=>$result,'user_ids'=>$user_ids];
    }

    /**
     * @desc 回复列表
     * */
    public function replys_list($comment_id,$page,$page_size)
    {
        $condition = ['comment_id' => $comment_id];
        $fields = [ 'id as reply_id','comment_id', 'reply_type', 'reply_content', 'reply_voice','from_user_id','to_user_id','create_timestamp', 'p_lng', 'p_lat', 'reply_voice_time','reply_img'];
        $document = DB::table($this->replyTable)
            ->where($condition)
            ->orderBy('create_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($fields);

        $result = self::objToArray($document);
        $f_user_ids = [];
        $t_user_ids = [];
        $reply_ids = [];
        if(!empty($result)){
            foreach($result as $k=>$v){
                if($v['reply_voice']){
                    $result[$k]['reply_voice'] = getPicDomain().$v['reply_voice'];
                }

                if($v['reply_img']){
                    $img_arr = explode(",",$v['reply_img']);
                    $thumb_img = [];
                    foreach ($img_arr as &$img){
                        $img = getPicDomain().$img;
                        array_push($thumb_img,$img."?x-oss-process=style/thumbnails");
                    }
                    unset($img);
                    //大图
                    $img_str = implode(",",$img_arr);
                    $result[$k]['reply_img'] = $img_str;

                    //缩略图
                    $thumb_str = implode(",",$thumb_img);
                    $result[$k]['thumb_reply_img'] = $thumb_str;
                }

                $f_user_ids[] = $v['from_user_id'];
                $t_user_ids[] = $v['to_user_id'];
                $reply_ids[] = $v['reply_id'];
            }
        }

        if(!empty($reply_ids)){
            $like_count_arr = $this->trends_reply_like_count($reply_ids);
        }

        if(!empty($result)){
            foreach($result as $k=>$v){
                $result[$k]['like_count'] = isset($like_count_arr[$v['reply_id']])?$like_count_arr[$v['reply_id']]:0;
            }
        }

        return ['list'=>$result,'f_user_ids'=>$f_user_ids,'t_user_ids'=>$t_user_ids];
    }

    /**
     * @desc 统计回复数
     * */
    public function reply_count(array $comment_ids)
    {
        $re_document = DB::table($this->replyTable)
            ->whereIn('comment_id',$comment_ids)
            ->groupBy('comment_id')
            ->select('comment_id',DB::raw('count(comment_id) as total_reply'))
            ->get();
        $temp = self::objToArray($re_document);
        $ret = [];
        if(!empty($temp)){
            foreach($temp as $k=>$v){
                $ret[$v['comment_id']] = $v['total_reply'];
            }
        }
        return $ret;
    }

    /**
     * @desc 获取统计项
     * */
    public function trends_count(array $content_ids)
    {
        $re_document = DB::table($this->countTable)
            ->whereIn('content_id',$content_ids)
            ->get();
        $ret = self::objToArray($re_document);
        return $ret;
    }

    /**
     * @desc 统计推荐
     * */
    public function trends_recomment_items($min_time)
    {
        global $temp;
        DB::table('trends_zpzy_count')->where('create_timestamp','>=',$min_time)->orderBy('id','desc')->chunk(100,function ($count){
            foreach($count as $key =>$val ){
                //单项满足
                if(($val->read_count >= 100) || ($val->like_count >= 20)  || ($val->comment_count >= 20)  || ($val->relay_count >= 20)){
                    $GLOBALS['temp'][] = $val->content_id;
                }
                //双项或以上满足一半
                $f = 0;
                if($val->read_count >= 50){
                    $f += 1;
                }
                if($val->like_count >= 10){
                    $f += 1;
                }
                if($val->comment_count >= 10){
                    $f += 1;
                }
                if($val->relay_count >= 10){
                    $f += 1;
                }
                if($f >= 2){
                    $GLOBALS['temp'][] = $val->content_id;
                }
            }
        });
        $ids = [];
        if(is_array($temp)){
            $ids = array_unique($temp);
            sort($ids);
        }
        return $ids;
    }

    /**
     * @desc 获取多个评论点赞数
     * */
    public function trends_comment_like_count(array $comment_ids)
    {

        $re_document = DB::table($this->commentLikeTable)
            ->where(['is_cancel'=>0])
            ->whereIn('comment_id',$comment_ids)
            ->groupBy('comment_id')
            ->select('comment_id',DB::raw('count(comment_id) as total_like'))
            ->get();
        $temp = self::objToArray($re_document);
        $ret = [];
        if(!empty($temp)){
            foreach($temp as $k=>$v){
                $ret[$v['comment_id']] = $v['total_like'];
            }
        }
        return $ret;
    }


    /**
     * 获取回复点赞数
     * @param array $reply_ids
     * @return array
     */
    public function trends_reply_like_count(array $reply_ids)
    {

        $re_document = DB::table($this->replyLikeTable)
            ->where(['is_cancel'=>0])
            ->whereIn('reply_id',$reply_ids)
            ->groupBy('reply_id')
            ->select('reply_id',DB::raw('count(reply_id) as total_like'))
            ->get();
        $temp = self::objToArray($re_document);
        $ret = [];
        if(!empty($temp)){
            foreach($temp as $k=>$v){
                $ret[$v['reply_id']] = $v['total_like'];
            }
        }
        return $ret;
    }

    /**
     * 动态审核开关
     *
     * @param int $operateType 操作类型 默认0=读取，1=写入
     * @param int $status 是否关闭或开启 默认0=关闭，1=开启
     * @return bool
     * */
    public function trendsAuditSwitch($operateType = 0, $status = 0)
    {
        $result = 0;
        switch ($operateType) {
            case 0:
                if (Redis::exists($this->redisKeyTrendsAuditSwitch)) {
                    $result = intval(Redis::get($this->redisKeyTrendsAuditSwitch));
                }
                break;
            case 1:
                $ret = Redis::set($this->redisKeyTrendsAuditSwitch, $status);
                if ($ret) {
                    $result = $status;
                }
                break;
            default:
                break;
        }
        return $result;
    }

    /**
     * 动态更新
     *
     * @param int $contentId 内容ID
     * @param array $data 更新数据
     * @return bool
     * */
    public function trendsUpdate($contentId, $data)
    {
        return DB::table($this->table)->where(['content_id' => $contentId])->update($data);
    }

    /**
     * 动态增加推荐
     *
     * @param int $contentId 内容ID
     * @return bool
     * */
    public function trendsAddRecommend($contentId)
    {
        return Redis::HSET($this->redisKeyTrendsRECOMMEND, $contentId, time());
    }

    /**
     * 动态移除推荐
     *
     * @param int $contentId 内容ID
     * @return bool
     * */
    public function trendsRemoveRecommend($contentId)
    {
        return Redis::HDEL($this->redisKeyTrendsRECOMMEND, $contentId);
    }

    /**
     * 动态获取随机一个推荐动态数据
     *
     * @return array
     * */
    public function getTrendsRandomOneRecommend($gender)
    {
        $contentIdArray = Redis::HKEYS($this->redisKeyTrendsRECOMMEND);
        if (empty($contentIdArray)) {
            return [];
        }

        $content_ids = $this->getTrendsByIds($contentIdArray,$gender);
        // 动态ID数组顺序打乱随机
        shuffle($content_ids);

        // 返回数组中的随机键名
        $randKey = array_rand($content_ids);
        return $this->trend($content_ids[$randKey]);
    }

    /**
     * 获取动态阅读推送时间 1小时过去
     * @param int $contentId 内容ID
     * @param int $userId 用户ID
     * @return bool
     * */
    public function getTrendReadPushCache($contentId, $userId)
    {
        return Redis::GET($this->redisKeyTrendsReadLimit . $contentId . ":" . $userId);
    }

    /**
     * 设置 1小时过去
     * @param int $contentId 内容ID
     * @param int $userId 用户ID
     * @return bool
     * */
    public function setTrendReadPushCache($contentId, $userId)
    {
        return Redis::SET($this->redisKeyTrendsReadLimit . $contentId . ":" . $userId, $contentId, 'EX', 3600);
    }

    /**
     * @param  $contentId 动态ID
     * @param $page
     * @param $page_size
     * @return array
     * */
    public function getTrendLikeList($contentId, $page = 0, $page_size = 20)
    {
        $document = DB::table($this->likeTable)->where(['content_id'=>$contentId, 'is_cancel'=>0])
            ->orderBy('create_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get();
        return $document ? self::objToArray($document) : [];
    }

    /**
     * @param  $contentId 动态ID
     * @param $page
     * @param $page_size
     * @return int
     * */
    public function getTrendLikeCount($contentId)
    {
        return DB::table($this->likeTable)->where(['content_id'=>$contentId, 'is_cancel'=>0])
            ->count();
    }

    /**
     * @param $userId
     * @param $page
     * @param $page_size
     * @return int
     * */
    public function getTrendCountByUserId($userId)
    {
        return DB::table($this->table)
            ->where(['trends_content.user_id' => $userId, 'trends_content.is_delete' => 0])
            ->where('trends_content.create_timestamp', '<', 1577807999)
            ->count();
    }

    /**
     * @param $userId
     * @param $page
     * @param $page_size
     * @return int
     * */
    public function getTrendLikeCountByUserId($userId)
    {
        return DB::table($this->table)
            ->leftJoin($this->likeTable, 'trends_content.content_id', "=", 'trends_content_like.content_id')
            ->where(['trends_content.user_id' => $userId, 'trends_content.is_delete' => 0, 'trends_content_like.is_cancel' => 0])
            ->where('trends_content_like.id', '!=', null)
            ->where('trends_content.create_timestamp', '<', 1577807999)
            ->where('trends_content_like.create_timestamp', '<', 1577807999)
            ->count();
    }

    /**
     * @param $userId
     * @param $page
     * @param $page_size
     * @return int
     * */
    public function getTrendCommentCountByUserId($userId)
    {
        return DB::table($this->table)
            ->leftJoin($this->commentTable, 'trends_content.content_id', "=", 'trends_comment.content_id')
            ->where(['trends_content.user_id' => $userId, 'trends_content.is_delete' => 0])
            ->where('trends_comment.comment_id', '!=', null)
            ->where('trends_content.create_timestamp', '<', 1577807999)
            ->where('trends_comment.create_timestamp', '<', 1577807999)
            ->count();
    }

    public function getHandleTrendContentList($offset, $limit)
    {
        $result = DB::table($this->table)
            ->where(["is_delete" => 0])
            ->orderBy("trends_content.content_id", "asc")
            ->offset($offset)
            ->limit($limit)
            ->get(["content_id", "c_content"]);
        return $this->objToArray($result);
    }

    public function getHandleTrendCommentList($offset, $limit)
    {
        $result = DB::table($this->commentTable)
            ->orderBy("trends_comment.comment_id", "asc")
            ->offset($offset)
            ->limit($limit)
            ->get(["comment_id", "comment_text"]);
        return $this->objToArray($result);
    }

    /**
     * @desc 根据动态id和性别获取动态
     * */
    public function getTrendsByIds($contentIds ,$gender)
    {
        $fields = ['content_id'];
        $document = DB::table($this->table)
            ->where(['is_delete' => 0, 'state' => 1 ,'gender_type'=>$gender])
            ->whereIn('content_id' ,$contentIds)
            ->get($fields);
        $result = self::objToArray($document);
        return $result;
    }

    /**获取动态-上一次筛选内容
     * @param $user_id
     * @return mixed
     */
    public function getLastSelectGender($user_id){
        return Redis::HGET($this->redisTrendsLastSelectGender ,$user_id);
    }

    /**设置动态-上一次筛选内容
     * @param $user_id
     * @param $gender
     */
    public function setLastSelectGender($user_id ,$gender){
        Redis::HSET($this->redisTrendsLastSelectGender ,$user_id ,$gender);
    }

    public function getGreetUser($trend_id){
        $user_ids = Redis::HGET($this->redisTrendsGreet ,$trend_id);
        return !empty($user_ids) ? json_decode($user_ids ,true) : [];
    }

    public function setGreetUser($trend_id ,$user_id){
        $user_ids = Redis::HGET($this->redisTrendsGreet ,$trend_id);
        if(!empty($user_ids)){
            $user_ids = json_decode($user_ids ,true);
        }
        $user_ids[] = $user_id;
        Redis::HSET($this->redisTrendsGreet ,$trend_id ,json_encode($user_ids));
        $this->addGreetLog($trend_id,$user_id);
    }

    public function addGreetLog($trend_id,$user_id){
        try {
            DB::table($this->trendGreetLogTable)->insert([
                'user_id' => $user_id,
                'trend_id' => $trend_id,
            ]);
        }catch (\Exception $exception){
            write_log('Trend','addGreetLog Error', ['trend_id'=>$trend_id,'user_id'=>$user_id] );
            write_log('Trend','addGreetLog Error', $exception->getMessage() );
        }
    }

    /**curd 动态推荐
     * @param string $type
     * @param $data
     * @return int
     */
    public function curdTrendsAd($type='insert',$data){
        $operate_id = isset($data['id']) ? $data['id'] : 0;
        switch ($type){
            case 'insert':
                $operate_id = DB::table($this->trendsAdTable)->insertGetId($data);
                break;
            case 'update':
                unset($data['id']);
                DB::table($this->trendsAdTable)
                    ->where('id' ,$operate_id)
                    ->update($data);
                break;
            case 'del':
                DB::table($this->trendsAdTable)->where('id',$operate_id)->delete();
                break;
        }
        Redis::del($this->redisTrendsAd);
        return $operate_id;
    }

    /**家族动态
     * @param $page
     * @param $page_size
     * @param $ids
     * @return mixed
     */
    public function trends_family_list($page,$page_size,$ids,$is_show_works = false)
    {
        //判断作品，低版本不显示作品
        if(!$is_show_works){
            $document = DB::table($this->table)
                ->where(['is_delete'=>0, 'state' => 1])
                ->where('c_type' ,'!=' ,6)
                ->whereIn('user_id',$ids)
                ->where('create_timestamp','>=' ,time()-7*24*60*60)
                ->orderBy('create_timestamp', 'desc')
                ->offset(($page) * $page_size)
                ->limit($page_size)
                ->get($this->fields);
        }else{
            $document = DB::table($this->table)
                ->where(['is_delete'=>0, 'state' => 1])
                ->whereIn('user_id',$ids)
                ->where('create_timestamp','>=' ,time()-7*24*60*60)
                ->orderBy('create_timestamp', 'desc')
                ->offset(($page) * $page_size)
                ->limit($page_size)
                ->get($this->fields);
        }
        $result = self::objToArray($document);
        $result = $this->resource_build($result);
        return $result;
    }

    /**
     * @desc 根据动态id获取动态
     * */
    public function getTrendsByContentIds($contentIds)
    {
        $document = DB::table($this->table)
            ->where(['is_delete' => 0, 'state' => 1 ,'m_type' => 2])
            ->whereIn('content_id' ,$contentIds)
            ->get($this->fields);
        $res = self::objToArray($document);
        return $this->resource_build($res);
    }

    /**
     * 最近的动态
     */
    public function latelyTrends(int $userId, array $fields = ['*']): array {
        $res = DB::table($this->table)->where(['user_id' => $userId,'is_delete' => 0, 'state' => 1, 'c_type' => 2])->orderBy('content_id', 'desc')->limit(4)->get($fields);
        if(!$res) return [];
        $res = self::objToArray($res);
        $res = $this->resource_build($res);
        foreach($res as &$item) {
            $item['c_imgs'] = (isset($item['c_imgs']) && $item['c_imgs']) ? explode(',', $item['c_imgs']) : [];
            $item['c_thumbnails_imgs'] = (isset($item['c_thumbnails_imgs']) && $item['c_thumbnails_imgs']) ? explode(',', $item['c_thumbnails_imgs']) : [];
        }
        unset($item);
        return $res;
    }

    /**
     * 扩列-在线用户列表
     *
     * Created at 2021/10/18 10:38
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $userId
     * @return array
     */
    public function getLatelyTrendsFromCache(int $userId): array
    {
        $cacheKey = 'LATELY:TRENDS:NEW:USER:' . $userId;
        $cache = Redis::GET($cacheKey);
        if ($cache) {
            return json_decode($cache, true);
        }

        $latelyTrends = $this->latelyTrends($userId, ['c_imgs']);
        $trends = [];
        $expectTotal = 4;
        if ($latelyTrends) {
            foreach ($latelyTrends as $item) {
                $thumbnailsImages = $item['c_thumbnails_imgs'];
                if ($thumbnailsImages) {
                    foreach ($thumbnailsImages as $thumbnailsImage) {
                        $trends[] = $thumbnailsImage;
                    }
                }
            }

            $trends = array_slice($trends, 0, 4);
            if (count($trends) != $expectTotal) {//不足，重置为空
                $trends = [];
            }
        }

        Redis::SET($cacheKey, json_encode($trends));
        Redis::EXPIRE($cacheKey, 10 * 60 + rand(1, 60));
        return $trends;
    }

    /**
     * 检测用户是否有动态
     *
     * Created at 2021/10/18 11:24
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $userId
     * @return bool
     */
    public function checkUserTrends(int $userId): bool
    {
        $cacheKey = 'LATELY:TRENDS:USER:EXIST:' . $userId;
        $cache = Redis::GET($cacheKey);
        if ($cache) {
            return intval($cache) == 1 ? true : false;
        }

        $trend = self::query()->where(['user_id' => $userId, 'state' => 1, 'is_delete' => 0])->limit(1)->first();//动态
        $bool = $trend ? true : false;
        Redis::SET($cacheKey, $bool ? 1 : 0);
        Redis::EXPIRE($cacheKey, 10 * 60 + rand(1, 60));
        return $bool;
    }

    public function getUserIdByContentId(int $contentId) : ?int
    {
        $condition = array('content_id'=>$contentId);
        $re = $this->getOneByCondition($condition, array('user_id'));
        if ($re) {
            return $re['user_id'];
        }
        return null;
    }
}
